{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e82d5c2a",
   "metadata": {},
   "source": [
    "降维就是一种对高维度特征数据预处理方法。降维是将高维度的数据保留下最重要的一些特征，去除噪声和不重要的特征，从而实现提升数据处理速度的目的。在实际的生产和应用中，降维在一定的信息损失范围内，可以为我们节省大量的时间和成本。降维也成为应用非常广泛的数据预处理方法。\n",
    "\n",
    "PCA 就是这样的降维方法"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "171f37c6",
   "metadata": {},
   "source": [
    "PCA(Principal Component Analysis)，即主成分分析方法，是一种使用最广泛的数据降维算法。PCA的主要思想是将n维特征映射到k维上，这k维是全新的正交特征也被称为主成分，是在原有n维特征的基础上重新构造出来的k维特征。PCA的工作就是从原始的空间中顺序地找一组相互正交的坐标轴，新的坐标轴的选择与数据本身是密切相关的。其中，第一个新坐标轴选择是原始数据中方差最大的方向，第二个新坐标轴选取是与第一个坐标轴正交的平面中使得方差最大的，第三个轴是与第1,2个轴正交的平面中方差最大的。依次类推，可以得到n个这样的坐标轴。通过这种方式获得的新的坐标轴，我们发现，大部分方差都包含在前面k个坐标轴中，后面的坐标轴所含的方差几乎为0。于是，我们可以忽略余下的坐标轴，只保留前面k个含有绝大部分方差的坐标轴。事实上，这相当于只保留包含绝大部分方差的维度特征，而忽略包含方差几乎为0的特征维度，实现对数据特征的降维处理。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a2ffaac4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 1.0922184   1.7104114 ]\n",
      " [-3.4805083  -0.08995552]\n",
      " [ 2.25756044 -0.92597504]\n",
      " [ 0.13072946 -0.69448083]]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.decomposition import PCA\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "data = [\n",
    "    # [最大速度, 飞行半径, 最大负载, 费用, 可靠性, 灵敏度]\n",
    "    [2.0, 1500, 20000, 5500000, 0.5, 1.0],  # A1\n",
    "    [2.5, 2700, 18000, 6500000, 0.3, 0.5],  # A2\n",
    "    [1.8, 2000, 21000, 4500000, 0.7, 0.7],  # A3\n",
    "    [2.2, 1800, 20000, 5000000, 0.5, 0.5],  # A4\n",
    "]\n",
    "\n",
    "aircraft_names = [\"A1\", \"A2\", \"A3\", \"A4\"]\n",
    "indicator_names = [\"最大速度\", \"飞行半径\", \"最大负载\", \"费用\", \"可靠性\", \"灵敏度\"]\n",
    "\n",
    "df = pd.DataFrame(data=data, columns=indicator_names, index=aircraft_names)\n",
    "\n",
    "X = np.array(data)\n",
    "\n",
    "X = StandardScaler().fit_transform(X)\n",
    "\n",
    "pca = PCA(n_components=2)\n",
    "X_reduced = pca.fit_transform(X)\n",
    "\n",
    "print(X_reduced)  # 降维后的结果"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "cdd3a812",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0.76752285, 0.17805552])"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pca.explained_variance_ratio_ # 各主成分的方差百分比"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8c36ff88",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "============================================================\n",
      "【PCA主成分分析详细结果】\n",
      "============================================================\n",
      "第一主成分解释方差比例: 0.7675 (76.75%)\n",
      "第二主成分解释方差比例: 0.1781 (17.81%)\n",
      "累计解释方差比例: 0.9456 (94.56%)\n",
      "\n",
      "【主成分载荷矩阵】\n",
      "----------------------------------------\n",
      "       第一主成分   第二主成分\n",
      "最大速度 -0.4546  0.0012\n",
      "飞行半径 -0.3699 -0.4130\n",
      "最大负载  0.4592 -0.1602\n",
      "费用   -0.4260  0.3744\n",
      "可靠性   0.4405 -0.2767\n",
      "灵敏度   0.2647  0.7662\n",
      "\n",
      "【各指标对主成分的贡献率】\n",
      "----------------------------------------\n",
      "      对PC1贡献率  对PC2贡献率\n",
      "最大速度   0.0337   0.0000\n",
      "飞行半径   0.0223   0.1197\n",
      "最大负载   0.0343   0.0180\n",
      "费用     0.0296   0.0984\n",
      "可靠性    0.0316   0.0537\n",
      "灵敏度    0.0114   0.4121\n",
      "\n",
      "【降维后的主成分得分】\n",
      "----------------------------------------\n",
      "    第一主成分得分  第二主成分得分\n",
      "A1   1.0922   1.7104\n",
      "A2  -3.4805  -0.0900\n",
      "A3   2.2576  -0.9260\n",
      "A4   0.1307  -0.6945\n",
      "\n",
      "【基于PCA的综合评价模型】\n",
      "----------------------------------------\n",
      "    第一主成分得分  第二主成分得分    综合得分   标准化得分  排名\n",
      "A1   1.0922   1.7104  1.1429  0.9001 NaN\n",
      "A2  -3.4805  -0.0900 -2.6874  0.0000 NaN\n",
      "A3   2.2576  -0.9260  1.5679  1.0000 NaN\n",
      "A4   0.1307  -0.6945 -0.0233  0.6261 NaN\n",
      "\n",
      "【PCA评价模型分析报告】\n",
      "==================================================\n",
      " 数据概况:\n",
      "   - 原始维度: 6维\n",
      "   - 降维后维度: 2维\n",
      "   - 信息保留率: 94.56%\n",
      "\n",
      " 排名结果:\n",
      "   第1名: A3 (得分: 1.5679)\n",
      "   第2名: A1 (得分: 1.1429)\n",
      "   第3名: A4 (得分: -0.0233)\n",
      "   第4名: A2 (得分: -2.6874)\n",
      "\n",
      " 主成分解释:\n",
      "   - 第一主成分(PC1): 解释76.75%的方差\n",
      "     主要反映指标: 最大负载(0.459), 最大速度(0.455), 可靠性(0.441)\n",
      "   - 第二主成分(PC2): 解释17.81%的方差\n",
      "     主要反映指标: 灵敏度(0.766), 飞行半径(0.413), 费用(0.374)\n",
      "\n",
      "建议:\n",
      "   - 推荐选择: A3\n",
      "   - 该飞机在综合评价中表现最佳，平衡了各项性能指标\n"
     ]
    }
   ],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "# 设置中文字体\n",
    "plt.rcParams[\"font.sans-serif\"] = [\"SimHei\", \"DejaVu Sans\"]\n",
    "plt.rcParams[\"axes.unicode_minus\"] = False\n",
    "\n",
    "print(\"=\" * 60)\n",
    "print(\"【PCA主成分分析详细结果】\")\n",
    "print(\"=\" * 60)\n",
    "\n",
    "# 1. 各主成分的方差解释比例\n",
    "print(\n",
    "    f\"第一主成分解释方差比例: {pca.explained_variance_ratio_[0]:.4f} ({pca.explained_variance_ratio_[0]*100:.2f}%)\"\n",
    ")\n",
    "print(\n",
    "    f\"第二主成分解释方差比例: {pca.explained_variance_ratio_[1]:.4f} ({pca.explained_variance_ratio_[1]*100:.2f}%)\"\n",
    ")\n",
    "print(\n",
    "    f\"累计解释方差比例: {pca.explained_variance_ratio_.sum():.4f} ({pca.explained_variance_ratio_.sum()*100:.2f}%)\"\n",
    ")\n",
    "\n",
    "# 2. 主成分载荷矩阵(各原始指标对主成分的贡献)\n",
    "print(\"\\n【主成分载荷矩阵】\")\n",
    "print(\"-\" * 40)\n",
    "components_df = pd.DataFrame(\n",
    "    pca.components_.T, columns=[\"第一主成分\", \"第二主成分\"], index=indicator_names\n",
    ")\n",
    "print(components_df.round(4))\n",
    "\n",
    "# 3. 计算各指标对主成分的贡献率\n",
    "print(\"\\n【各指标对主成分的贡献率】\")\n",
    "print(\"-\" * 40)\n",
    "# 贡献率 = (载荷值^2) / 特征值\n",
    "eigenvalues = pca.explained_variance_\n",
    "contribution_rates = pd.DataFrame(\n",
    "    (pca.components_.T**2) / eigenvalues,\n",
    "    columns=[\"对PC1贡献率\", \"对PC2贡献率\"],\n",
    "    index=indicator_names,\n",
    ")\n",
    "print(contribution_rates.round(4))\n",
    "\n",
    "# 4. 原始数据在主成分空间的坐标\n",
    "print(\"\\n【降维后的主成分得分】\")\n",
    "print(\"-\" * 40)\n",
    "pc_scores_df = pd.DataFrame(\n",
    "    X_reduced, columns=[\"第一主成分得分\", \"第二主成分得分\"], index=aircraft_names\n",
    ")\n",
    "print(pc_scores_df.round(4))\n",
    "\n",
    "# 5. 构建基于PCA的综合评价模型\n",
    "print(\"\\n【基于PCA的综合评价模型】\")\n",
    "print(\"-\" * 40)\n",
    "\n",
    "# 使用主成分得分和方差解释比例计算综合得分\n",
    "weights = pca.explained_variance_ratio_  # 以方差解释比例作为权重\n",
    "comprehensive_scores = np.dot(X_reduced, weights)\n",
    "\n",
    "# 标准化到0-1区间\n",
    "min_score = comprehensive_scores.min()\n",
    "max_score = comprehensive_scores.max()\n",
    "normalized_scores = (comprehensive_scores - min_score) / (max_score - min_score)\n",
    "\n",
    "# 创建评价结果DataFrame\n",
    "evaluation_results = pd.DataFrame(\n",
    "    {\n",
    "        \"第一主成分得分\": X_reduced[:, 0],\n",
    "        \"第二主成分得分\": X_reduced[:, 1],\n",
    "        \"综合得分\": comprehensive_scores,\n",
    "        \"标准化得分\": normalized_scores,\n",
    "        \"排名\": pd.Series(comprehensive_scores).rank(ascending=False).astype(int),\n",
    "    },\n",
    "    index=aircraft_names,\n",
    ")\n",
    "\n",
    "print(evaluation_results.round(4))\n",
    "# 7. 生成详细报告\n",
    "print(\"\\n【PCA评价模型分析报告】\")\n",
    "print(\"=\" * 50)\n",
    "print(f\" 数据概况:\")\n",
    "print(f\"   - 原始维度: {X.shape[1]}维\")\n",
    "print(f\"   - 降维后维度: 2维\")\n",
    "print(f\"   - 信息保留率: {pca.explained_variance_ratio_.sum()*100:.2f}%\")\n",
    "\n",
    "print(f\"\\n 排名结果:\")\n",
    "ranking = evaluation_results.sort_values(\"综合得分\", ascending=False)\n",
    "for i, (aircraft, row) in enumerate(ranking.iterrows(), 1):\n",
    "    print(f\"   第{i}名: {aircraft} (得分: {row['综合得分']:.4f})\")\n",
    "\n",
    "print(f\"\\n 主成分解释:\")\n",
    "print(f\"   - 第一主成分(PC1): 解释{pca.explained_variance_ratio_[0]*100:.2f}%的方差\")\n",
    "print(f\"     主要反映指标: \", end=\"\")\n",
    "pc1_important = components_df[\"第一主成分\"].abs().nlargest(3)\n",
    "print(\", \".join([f\"{idx}({val:.3f})\" for idx, val in pc1_important.items()]))\n",
    "\n",
    "print(f\"   - 第二主成分(PC2): 解释{pca.explained_variance_ratio_[1]*100:.2f}%的方差\")\n",
    "print(f\"     主要反映指标: \", end=\"\")\n",
    "pc2_important = components_df[\"第二主成分\"].abs().nlargest(3)\n",
    "print(\", \".join([f\"{idx}({val:.3f})\" for idx, val in pc2_important.items()]))\n",
    "\n",
    "print(f\"\\n建议:\")\n",
    "best_aircraft = ranking.index[0]\n",
    "print(f\"   - 推荐选择: {best_aircraft}\")\n",
    "print(f\"   - 该飞机在综合评价中表现最佳，平衡了各项性能指标\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "math_env",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
